#!/usr/bin/python2.4
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""gets a list of unix groups and dumps in in user permission directories.

This script dumps all your available groups reachable by your NSS configuration
(/etc/nsswitch.conf), which means local files, NIS, LDAP, filedb, and others

It then compiles a list of groups for each available user and dumps that list
of groups either in a hashed list of user directories
(it's obviously trivial to modify the script to output to any kind of file
or format you'd like)

Some parts of this code are specific to our configuration, take it as a sample
that you can modify
"""


import grp
import os
import gvn.userdb

# Change this for your local install
SVN_USERDB_PATH = "/opt/svn/userdb"

def main():
  userdbdict = {}
  userdb = gvn.userdb.UserDB(SVN_USERDB_PATH)

  # NOTE: this only lists unix groups, we may also want to iterate through
  # ldap only groups, not that it also only shows secondary groups, modify
  # as required for your setup
  for grpline in grp.getgrall():
    grpname, _, _, grpusers = grpline
    # skip former users
    if grpname == "former":
      continue
    for user in grpusers:
      if user in userdbdict:
        userdbdict[user].append(grpname)
      else:
        userdbdict[user] = [grpname]

  for user in userdbdict:
    if not userdb.DoesUserExist(user):
      print "Adding new user " + user
    userdb.WriteUserGroups(user, userdbdict[user])

  for user in userdb.GetAllUsers(require_password=False,
                                                return_not_autosynced=False):
    # delete all users that don't have any groups (this might not be what you
    # want, but for us, groupless users aren't users anymore)
    # return_not_autosynced=False so that we ignore svn only users and do not
    # delete them because they aren't in the unix userdb
    if user not in userdbdict:
      userdb.DeleteUser(user)
      print "deleting former user " + user



if __name__ == '__main__':
  main()
